import 'dart:async';
import 'dart:convert';
import 'package:deepseek_client/ai/service/chat_service.dart';
import 'package:deepseek_client/common/EventBus.dart';
import 'package:deepseek_client/common/SpConstants.dart';
import 'package:deepseek_client/common/controller/IAppController.dart';
import 'package:deepseek_client/common/event/event.dart';
import 'package:deepseek_client/common/utils/SpUtils.dart';
import 'package:deepseek_client/extensions/PlatformExtensions.dart';
import 'package:deepseek_client/page/ModelSelectPage.dart';
import 'package:deepseek_client/widget/AutoMarquee.dart';
import 'package:deepseek_client/widget/MainLeftDrawer.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:swipeable_page_route/swipeable_page_route.dart';

import 'package:tdesign_flutter/tdesign_flutter.dart';

import 'HomePage.dart';

class MainPage extends StatefulWidget {
  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> implements IAppController {
  final ValueNotifier<bool> _drawerOpenNotifier = ValueNotifier<bool>(false);
  final ValueNotifier<String> _titleNotifier = ValueNotifier<String>("新会话");
  final List<TDDropdownItemOption> _modelItemOptions = [];
  final List<TDDropdownItemOption> _aiServicePlatform = [
    TDDropdownItemOption(value: "Ollama", label: "Ollama" , selected: true),
    TDDropdownItemOption(value: "Gemini", label: "Gemini"),
    TDDropdownItemOption(value: "VolcEngine", label: "VolcEngine"),
  ];
  CancelToken? _msgCancelToken;
  StreamSubscription? _historyClearTask;
  StreamSubscription? _collapseHistoryTask;
  IChatService? _chatService;
  String serviceType = "";

  @override
  void initState() {
    super.initState();
    _initAiService(checkCached: true).then((value){
      findModels();
    });
    _historyClearTask = eventBus.on<HistoryClearEvent>().listen((event) async {
      _drawerOpenNotifier.value = false;
    });
    _collapseHistoryTask = eventBus.on<CollapseHistoryEvent>().listen((event){
      _drawerOpenNotifier.value = false;
    });
  }

  _initAiService({bool checkCached = false}) async {
    if(checkCached){
      serviceType = await SpUtils.getInstance().getString(SpConstants.serviceType);
      if(serviceType.isEmpty){
        _chatService = OllamaChatService();
        return;
      }
    }
    if(serviceType == "Gemini"){
      _chatService = GeminiChatService();
    }else if(serviceType == "VolcEngine"){
      _chatService = VolcEngineService();
    }else{
      _chatService = OllamaChatService();
    }
  }

  findModels() async {
    var res = await _chatService?.findModels();
    List<AiModel> _supportModels = res ?? [];
    _modelItemOptions.clear();
    var localModel = await SpUtils.getInstance().getString(SpConstants.model);
    for (var model in _supportModels) {
      var index = _supportModels.indexOf(model);
      if (localModel.isEmpty) {
        _modelItemOptions.add(TDDropdownItemOption(
            label: model.name ?? "模型名称",
            value: model.name ?? "",
            selected: index == 0));
        if (_supportModels.isNotEmpty) {
          await SpUtils.getInstance().put(SpConstants.model, _supportModels.first.name ?? "");
        }
        localModel = _supportModels.first.name ?? "";
      } else {
        _modelItemOptions.add(TDDropdownItemOption(
            label: model.name ?? "模型名称",
            value: model.name ?? "",
            selected: localModel == model.name));
      }
    }

    setState(() {

    });
  }

  loadModel() async {
    var request = {
      "model": _modelItemOptions.firstOrNull?.label,
      "messages": []
    };
    if (_msgCancelToken != null) {
      _msgCancelToken?.cancel("cancel by system");
    }
    _msgCancelToken = CancelToken();
    // client?.chat(_msgCancelToken!, json.encode(request)).then((res) {
    //   print("模型加载成功");
    // });
  }

  @override
  void dispose() {
    _titleNotifier.dispose();
    _collapseHistoryTask?.cancel();
    _historyClearTask?.cancel();
    _drawerOpenNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 返回一个Scaffold，它是Material Design中的一种基本布局结构
    var screenWidth = MediaQuery.of(context).size.width;
    return PopScope(
        canPop: false,
        onPopInvokedWithResult: (didPop, result) {
          if (didPop || _drawerOpenNotifier.value) {
            _drawerOpenNotifier.value = false;
            return;
          }
          SystemNavigator.pop(animated: true);
        },
        child: Scaffold(
          // 设置背景颜色为白色
          backgroundColor: Colors.white,
          appBar: isPhone
              ? AppBar(
                  // 使用ValueListenableBuilder监听_titleNotifier的变化，动态更新AppBar的标题
                  title: ValueListenableBuilder(
                      valueListenable: _titleNotifier,
                      builder: (context, title, child) {
                        return Container(
                          alignment: AlignmentDirectional.center,
                          width: screenWidth /  2,
                          child: AutoMarquee(value: title, style: const TextStyle(
                            color: Color(0xFF141414),
                            fontSize: 20,
                            fontWeight: FontWeight.w600,
                          ),
                          ),
                        );
                      }),
                  // 标题居中
                  centerTitle: true,
                  // 设置AppBar的阴影为0，即无阴影
                  elevation: 0,
                  // 设置AppBar的背景颜色为白色
                  backgroundColor: Colors.white,
                  leading: IconButton(
                      onPressed: () async {
                        // 切换抽屉的打开状态
                        _drawerOpenNotifier.value =
                        !_drawerOpenNotifier.value;
                        // 如果抽屉打开，则触发更新会话历史的事件
                        if (_drawerOpenNotifier.value) {
                          eventBus.fire(UpdateConversationHistoryEvent());
                        }
                      },
                      icon: const Icon(
                        Icons.history,
                        color: Colors.black,
                      )),
                  // 右侧操作按钮
                  actions: [
                    IconButton(
                        onPressed: () async {
                          eventBus.fire(OnModelSelectTapEvent());
                          Navigator.of(context).push(SwipeablePageRoute(builder: (context) => ModelSelectPage(service: _chatService))).then((res){
                            Timer(const Duration(milliseconds: 500), (){
                              eventBus.fire(RequestFocusEvent());
                            });
                          });
                        },
                        icon: const Icon(
                          Icons.menu,
                          color: Colors.black,
                        ))
                  ],
                )
              : null, // 如果不是Android或iOS平台，则不显示AppBar
          body: SafeArea(
              child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            physics: const NeverScrollableScrollPhysics(),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 使用ValueListenableBuilder监听_drawerOpenNotifier的变化，动态更新左侧抽屉的显示状态
                ValueListenableBuilder(
                    valueListenable: _drawerOpenNotifier,
                    builder: (context, isOpen, child) {
                      return MainLeftDrawer(
                        isOpen: isOpen,
                      );
                    }),
                Stack(
                  children: [
                    // 主页内容
                    HomePage(screenWidth: screenWidth, parentController: this , service: _chatService),
                    // 如果不是Android或iOS平台，则显示一个包含历史记录按钮和下拉菜单的容器
                    if (isNotPhone)
                      Container(
                        alignment: AlignmentDirectional.centerStart,
                        height: 60,
                        padding: const EdgeInsets.only(left: 20),
                        color: Colors.white,
                        child: Row(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            if(kDebugMode)GestureDetector(
                              onTap: () async {
                                SpUtils.getInstance().clear();
                                TDToast.showText("清除成功", context: context);
                              },
                              child: const Icon(
                                Icons.cleaning_services_rounded,
                                color: Colors.grey,
                              ),
                            ),
                            // 历史记录按钮
                            GestureDetector(
                              onTap: () async {
                                // 切换抽屉的打开状态
                                _drawerOpenNotifier.value =
                                    !_drawerOpenNotifier.value;
                                // 如果抽屉打开，则触发更新会话历史的事件
                                if (_drawerOpenNotifier.value) {
                                  eventBus.fire(UpdateConversationHistoryEvent());
                                }
                              },
                              child: const Icon(
                                Icons.history,
                                color: Colors.grey,
                              ),
                            ),
                            const SizedBox(
                              width: 10,
                            ),
                            if(_aiServicePlatform.isNotEmpty)
                              SizedBox(
                                width: 240,
                                height: 40,
                                child: TDDropdownMenu(
                                  direction: TDDropdownMenuDirection.down,
                                  onMenuOpened: (value) {
                                    // 打开菜单时的回调
                                    // print('打开第$value个菜单');
                                  },
                                  onMenuClosed: (value) {
                                    // 关闭菜单时的回调
                                    // print('关闭第$value个菜单');
                                  },
                                  items: [
                                    TDDropdownItem(
                                      options: _aiServicePlatform,
                                      onChange: (value) async {
                                        // 下拉菜单选项变化时的回调
                                        // 将选中的模型保存到SharedPreferences
                                        // await sharedPreferences?.setString(
                                        //     SpConstants.model, value[0]);
                                        SpUtils.getInstance().put(SpConstants.serviceType, value[0]);
                                        SpUtils.getInstance().put(SpConstants.model, "").then((res){
                                          serviceType = value[0];
                                          _initAiService();
                                          findModels();
                                          setState(() {

                                          });
                                        });
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            // 如果_modelItemOptions不为空，则显示下拉菜单
                            if (_modelItemOptions.isNotEmpty)
                              SizedBox(
                                width: 240,
                                height: 40,
                                child: TDDropdownMenu(
                                  direction: TDDropdownMenuDirection.down,
                                  onMenuOpened: (value) {
                                    // 打开菜单时的回调
                                    // print('打开第$value个菜单');
                                  },
                                  onMenuClosed: (value) {
                                    // 关闭菜单时的回调
                                    // print('关闭第$value个菜单');
                                  },
                                  items: [
                                    TDDropdownItem(
                                      options: _modelItemOptions,
                                      onChange: (value) async {
                                        // 下拉菜单选项变化时的回调
                                        // 将选中的模型保存到SharedPreferences
                                        // await sharedPreferences?.setString(
                                        //     SpConstants.model, value[0]);
                                        SpUtils.getInstance()
                                            .put(SpConstants.model, value[0]);
                                      },
                                    ),
                                  ],
                                ),
                              )
                          ],
                        ),
                      )
                  ],
                )
              ],
            ),
          )),
        ));
  }

  @override
  void setTitle(String title) {
    _titleNotifier.value = title;
  }
}
